package com.example.demo1.service;

import com.example.demo1.entity.User;
import com.example.demo1.mapper.UserMapper;
import com.example.demo1.util.PswdUtil;
import com.example.demo1.util.StringUtil;
import lombok.extern.log4j.Log4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

@Log4j
@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;

    public Map<String, Object> addUser(User user){

            System.out.println("addUser:"+user);
            //自增id
            /*user.setUser_id(UUIDUtil.getUUID());*/
            user.setUser_identity("5");
            String password = user.getPswd();
            String encodedPassword = PswdUtil.encode(password);
            user.setPswd(encodedPassword);
            log.info("准备添加用户: {}"+ user.getUser_name());
            int num = userMapper.addUser(user);
            log.info( num > 0 ? "成功" : "失败");
            Map<String, Object> result = new HashMap<>();
            result.put("success", num > 0); // 明确返回success字段（布尔值）
            result.put("message", num > 0 ? "注册成功" : "注册失败"); // 可选：返回提示信息
            return result;

    }

    public int deleteUser(Integer id){
            return userMapper.deleteUser(id);

    }

    public int updateUser(User user){
            return userMapper.updateUser(user);
    }

    public User selectUser(User user){
            return userMapper.selectUser(user);
    }

    public User selectUserByLo(User user){
        log.info("开始通过用户名查询用户: {}"+ user != null ? user.getUser_name() : "null");
        String userName = user.getUser_name();
        String password = user.getPswd();
        try {


            // 检查用户名和密码是否为空
            if (StringUtil.isEmpty(userName) || StringUtil.isEmpty(password)) {
                log.error("查询用户失败：用户名或密码不能为空");
                throw new IllegalArgumentException("用户名和密码不能为空");
            }
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }

            User aimUser = new User();
            aimUser = userMapper.selectUserByLo(user);
            log.info("***********"+aimUser);
            if(aimUser != null && PswdUtil.matches(password,aimUser.getPswd())){
                log.info("用户验证成功: {}"+ aimUser.getUser_name());
                aimUser.setPswd(null);
                return aimUser;

            }else {
                log.info("用户验证失败: 用户名或密码错误");
                return null;
            }



    }


    public ArrayList <User> selectUsers(User user){
            return userMapper.selectUsers(user);
        }

}
